<?php

namespace App\Http\Model;

use App\Http\Controllers\PublicController;
use Illuminate\Database\Eloquent\Model;

class OrderOrderModel extends Model
{
    protected $table = "pre_order";
    protected $connection = "order";

    public function create($add,$tmpRes,$total){
        $om = new OrderOrderModel();
        $public = new PublicController();
        $number = $public->uuid();

        \DB::beginTransaction();
        try{
            $om->number = $number;
            $om->user_id = $add["user_id"];
            $om->receiver_name = $add["name"];
            $om->receiver_province = $add["province"];
            $om->receiver_city = $add["city"];
            $om->receiver_district = $add["district"];
            $om->receiver_detail = $add["detail"];
            $om->receiver_mobile = $add["mobile"];
            $om->product_fee = $total[0];
            $om->express_fee = $total[1];
            $om->total_fee = $total[0]+$total[1];
            $om->status = 10;
            $om->save();

            $o_id = $om["id"];
            foreach($tmpRes as $t){
                $ooim = new OrderOrderItemModel();
                $ooim->order_id = $o_id;
                $ooim->product_id = $t["product"]["id"];
                $ooim->product_full_name = $t["product"]["name"];
                $ooim->sku_id = $t["sku"]["id"];
                $ooim->quantity = $t["quantity"];
                $ooim->price = $t["sku"]["price"];
                $ooim->save();


                $sm = OrderSkuModel::find($t["sku"]["id"]);
                $sm->quantity -= $t["quantity"];
                $sm->save();

                $pm = OrderProductModel::find($t["product"]["id"]);
                $pm->quantity -= $t["quantity"];
                $pm->save();
            }

            \DB::commit();

            return "success";
        } catch (Exception $e) {
            \DB::rollback();
            return "error";
        }

    }
}
